#!/bin/bash
clear

if [ "${EUID}" -ne 0 ]; then
    echo "You need to run this script as root" && exit 1
fi

TodayDate=$(date +"%Y-%m-%d")

function rclone_backup {
  echo " Enter Your Email To Receive Message"
  read -rp " Email: " -e email

  mkdir /root/backup

  cp /etc/passwd backup/
  cp /etc/group backup/
  cp /etc/shadow backup/
  cp /etc/gshadow backup/
  cp -r /usr/local/shadowsocksr/ backup/shadowsocksr
  cp -r /etc/trojan backup/trojan
  cp -r /etc/v2ray backup/v2ray
  cp -r /etc/wireguard backup/wireguard
  cp -r /home/vps/public_html backup/public_html
  cp -r /var/lib/premium-script/ backup/premium-script

  cd ~
  zip -r $IP-$date.zip backup > /dev/null 2>&1
  rclone copy /root/$IP-$date.zip dr:backup/
  url=$(rclone link dr:backup/$IP-$date.zip)
  id=(`echo $url | grep '^https' | cut -d '=' -f 2`)
  link="https://drive.google.com/u/4/uc?id=${id}&export=download"
  echo -e "The following is a link to your vps data backup file.

  Your VIRTUAL PRIVATE SERVER IP ADDRESS $IP

  $link

  If you want to restore data, please enter the link above." | mail -s "Backup Data" $email
  echo "Done, Please Check Your Email"

  rm -rf /root/backup
  rm -r /root/$IP-$date.zip
}

INFO="[ ENABLED ]" && ERROR="[ DISABLED ]"
checkCron=$( grep -c -E "^# BEGIN_Backup" /etc/crontab )
[[ "$checkCron" -eq 1 ]] && getStat="${INFO}" ||getStat="${ERROR}"

start() {
  email=$(cat /home/email)
  if [[ "$email" = "" ]]; then
    echo "Please enter your email"
    read -rp "Email: " -e email
cat << EOF >> /home/email
$email
EOF
  fi

  cat << EOF >> /etc/crontab
# BEGIN_Backup
5 0 * * * root backup.sh
# END_Backup
EOF
  service cron restart
  echo " Autobackup Has Been Started"
  echo " Data Will Be Backed Up Automatically at 00:05 GMT +0800" && exit 0
}

stop() {
  email=$(cat /home/email)
  sed -i "/^$email/d" /home/email
  sed -i "/^# BEGIN_Backup/,/^# END_Backup/d" /etc/crontab
  service cron restart
  echo " Autobackup Has Been Stopped" && exit 0
}

clear
echo
echo "=============================== [ AUTOBACKUP ]"
echo -e "Status $sts"
echo -e "01) start    - Start Autobackup"
echo -e "02) stop     - Stop Autobackup"
echo -e "==========================================="
read -rp "Enter your choice: " -e choose
case $choose in
    01|start )
        start && break
    ;;
    02|stop )
        stop && break
    ;;
    * )
        clear && echo "You Entered The Wrong Number"
    ;;
esac
